<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('order.quick Search Fields') })"
        >
            <!-- <el-button type="primary" style="margin-left: 12px" @click="simOrderDialog = true">
                模拟订单
            </el-button> -->
        </TableHeader>

        <Table ref="tableRef">
            <template #expandSlot>
                <el-table-column label="订单商品" :width="100" type="expand">
                    <template #default="props">
                        <el-table :data="props.row.goods" :border="childBorder" style="width: 70%;margin-left: 20px">
                            <el-table-column label="商品名称" prop="name" />
                            <el-table-column label="规格" prop="sku_name" />
                            <el-table-column label="实付单价" prop="price" />
                            <el-table-column label="数量" prop="num" />
                            <el-table-column label="小计" prop="total_price" />
                        </el-table>
                    </template>
                </el-table-column>
            </template>
        </Table>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->

        <!-- 表单 -->
        <PopupForm />

        <el-dialog
            v-model="write_show"
            title="自提核销"
            width="700"
        >
            <el-row>
                <el-col :span="18">
                    <FormItem label="提货码"  type="string" v-model="write_code"
                              :placeholder="t('Please input field', { field: t('提货码') })"/>
                </el-col>
                <el-col :span="5"><el-button style="margin-left: 5px" type="warning" @click="searchOrder">
                    查询
                </el-button></el-col>
            </el-row>

            <el-table :data="order_info.goods" style="width: 100%;height: 250px">
                <el-table-column prop="name" label="商品"  />
                <el-table-column prop="sku_name" width="130" label="规格" />
                <el-table-column prop="valid_num" width="100"  label="有效数量" />
            </el-table>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="write_show = false">取消</el-button>
                    <el-button type="primary" @click="sub_write">
                        核销
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="simOrderDialog" title="模拟订单" width="500">
            <el-form :model="simOrderForm" ref="simOrderFormRef" label-width="80px">
                <el-form-item label="用户" prop="user_id" :rules="[{ required: true, message: '请选择用户', trigger: 'change' }]">
                    <FormItem
                        type="remoteSelect"
                        v-model="simOrderForm.user_id"
                        :input-attr="{
                            pk: 'user.id',
                            field: 'nickname',
                            remoteUrl: '/admin/user.User/index',
                            remoteSearch: true,
                            placeholder: '请输入用户昵称/手机号搜索'
                        }"
                    />
                </el-form-item>
                <el-form-item label="商品" prop="id" :rules="[{ required: true, message: '请选择商品', trigger: 'change' }]">
                    <FormItem
                        type="remoteSelect"
                        v-model="simOrderForm.id"
                        :input-attr="{
                            pk: 'goods.id',
                            field: 'name',
                            remoteUrl: '/admin/Goods/index',
                            remoteSearch: true,
                            placeholder: '请输入商品名称搜索'
                        }"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="simOrderDialog = false">取消</el-button>
                <el-button type="primary" :loading="simOrderLoading" @click="onSimOrderSubmit">确定</el-button>
            </template>
        </el-dialog>

        <Info/>

        <DeliverDialog/>
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import Info from './info.vue'
import {auth, buildJsonToElTreeData} from "/@/utils/common";
import createAxios from "/@/utils/axios";
import {ElMessage, ElMessageBox, FormInstance} from "element-plus";
import moment from "moment/moment";
import DeliverDialog from './deliver.vue'
import FormItem from "/@/components/formItem/index.vue";
import {useAdminInfo} from "/@/stores/adminInfo";

defineOptions({
    name: 'order',
})

const { t } = useI18n()
const tableRef = ref()
const childBorder = ref(false)
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])

const info_auth = auth('info')
const restore_auth = auth('restore')
const deliver_auth = auth('deliver')

optButtons.push(
    {
        render: 'tipButton',
        name: 'info',
        title: '详情',
        text: '',
        type: 'primary',
        icon: 'fa fa-info-circle',
        click(row, field) {
            createAxios({
                url: '/admin/order/info?id='+row.id,
                method: 'get',
                data: {
                    id: row.id,
                }
            }, {
                loading: true
            }, {
                text: '加载中...'
            })
                .then((res) => {
                    if (res.code == 1) {
                        baTable.table.extend!.showInfo = true
                        baTable.table.extend!.infoData = res.data.row
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                })
                .catch((resx) => {
                })
        },
        display: (row, field) => {
            if (info_auth){
                return true;
            }
            return false;
        },
    },
    {
        render: 'confirmButton',
        name: 'restore',
        title: '备货完成',
        text: '',
        type: 'success',
        icon: 'fa fa-shopping-basket',
        class: 'table-row-edit',
        popconfirm: {
            confirmButtonText: t('确认'),
            cancelButtonText: t('取消'),
            confirmButtonType: 'success',
            title: t('确认已完成备货吗?'),
        },
        disabledTip: false,
        click: (row: TableRow) => {
            restore(row.id)
        },
        display: (row: TableRow, field: TableColumn) => {
            if (restore_auth && row.order_status == 10) {
                return true
            }
            return false
        },
    },
    {
        render: 'tipButton',
        name: 'deliver',
        title: '发货',
        text: '',
        type: 'warning',
        icon: 'el-icon-Van',
        class: 'table-row-info',
        disabledTip: false,
        click: (row: TableRow) => {
            deliverButtonClick(row[baTable.table.pk!])
        },
        display: (row: TableRow, field: TableColumn) => {
            if (deliver_auth && row.order_status == 15) {
                return true
            }
            return false
        },
    },
)

const baTable = new baTableClass(
    new baTableApi('/admin/Order/'),
    {
        pk: 'id',
        column: [
            {
                render: 'slot',
                slotName: 'expandSlot',
                operator: false,
            },
            { label: t('order.order_no'), width:200, prop: 'order_no', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('order.user__nickname'), width:100, prop: 'user.nickname', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },
            { label: t('order.order_money'), width:100, prop: 'order_money', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('order.goods_money'), width:100, prop: 'goods_money', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('order.pay_freight_money'), width:100, prop: 'pay_freight_money', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('order.pay_price'), width:100, prop: 'pay_price', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('order.balance'), width:100, prop: 'balance', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('order.cash_money'), width:100, prop: 'cash_money', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('order.carry_code'),show:false, prop: 'carry_code', align: 'center',  operator: 'eq', sortable: false },
            { label: t('order.pay_type'), width:100, prop: 'pay_type_text', align: 'center', operator: false, sortable: false },
            { label: t('order.order_status'), width:100, prop: 'order_status', align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue: { '1': t('order.order_status 1'),  '15': t('order.order_status 15'), '20': t('order.order_status 20'),  '30': t('order.order_status 30'), '90': t('order.order_status 90') } },
            { label: t('order.pay_time'), prop: 'pay_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('order.create_time'), prop: 'create_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false ,
                fixed: 'right'},
        ],
        dblClickNotEditColumn: [],
    },
    {
        defaultItems: { order_type: '1', order_no: null, send_style: 1, order_money: 0, goods_money: 0, pay_price: 0, cash_pay: 0, before_pay: 0, pay_freight_money: 0, vip_money: 0, pay_time: 0, name: null, mobile: null, city: null, area: null, address: null, carry_code: null, user_remarks: null, pay_type: '1', order_status: '1', old_order_status: null, pay_status: '1', cancel_time: 0, deliver_time: 0, receive_time: 0, express_code: null, express_name: null, express_no: null, express_data: null, over_time: 0, user_del_time: 0 },
    }
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})

const restore = (id: string) => {
    createAxios({
        url: '/admin/order/restore',
        method: 'post',
        data: {
            id: id,
        }
    }, {
        loading: true
    }, {
        text: '提交中...'
    })
        .then((res) => {
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            baTable.onTableHeaderAction('refresh', {})
        })
        .catch((resx) => {
        })
}

const deliverButtonClick = (id: string) => {
    baTable.form.extend!['deliver'] = {}
    baTable.form.operate = 'deliver'
    baTable.form.loading = true
    createAxios({
        url: '/admin/order/deliver',
        method: 'get',
        params: {
            id: id,
        },
    }).then((res) => {
        res.data.row.data = res.data.row.data
            ? [{
                label: t('security.dataRecycleLog.Click to expand'),
                children: buildJsonToElTreeData(res.data.row.data)
            }]
            : []
        baTable.form.extend!['info'] = res.data.row
        baTable.form.loading = false
    })
}

const write_show = ref(false);
const write_code = ref();
const order_info = ref({goods:[]});
const searchOrder = () => {
    createAxios({
        url: '/admin/order/write?write_code='+write_code.value,
        method: 'get',
        data: {}
    }, {
        loading: true
    }, {
        text: '查询中...'
    })
        .then((res) => {
            order_info.value = res.data.row;
        })
        .catch((resx) => {
            order_info.value.goods = [];
            return false;
        })
}
const sub_write = () => {
    createAxios({
        url: '/admin/order/write',
        method: 'post',
        data: {
            write_code: write_code.value,
        }
    }, {
        loading: true
    }, {
        text: '核销中...'
    })
        .then((res) => {
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            write_show.value = false;
            write_code.value = '';
            order_info.value.goods = [];
            baTable.onTableHeaderAction('refresh', {})
        })
        .catch((resx) => {
        })
}

const simOrderDialog = ref(false)
const simOrderForm = ref({ user_id: '', id: '' })
const simOrderFormRef = ref<FormInstance>()
const simOrderLoading = ref(false)

const onSimOrderSubmit = () => {
    simOrderFormRef.value?.validate((valid: boolean) => {
        if (!valid) return
        simOrderLoading.value = true
        createAxios({
            url: '/admin/order/simulatedorder',
            method: 'post',
            data: simOrderForm.value
        }, { loading: true }, { text: '提交中...' })
            .then(res => {
                ElMessage.success(res.msg || '操作成功')
                simOrderDialog.value = false
                simOrderForm.value = { user_id: '', id: '' }
                baTable.onTableHeaderAction('refresh', {})
            })
            .catch(() => {})
            .finally(() => { simOrderLoading.value = false })
    })
}
</script>

<style scoped lang="scss"></style>
